<?php
namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Log;

/**
 * DB事件监听器
 * Class QueryListener
 * @package App\Events
 */
class QueryListener
{
    public function handle(QueryExecuted $executed) {
        try{
            if (env('APP_SQL_DEBUG') == true) {
                $sql = str_replace("?", "'%s'", $executed->sql);
                foreach ($executed->bindings as $i => $binding) {
                    if ($binding instanceof \DateTime) {
                        $executed->bindings[$i] = $binding->format('Y-m-d H:i:s');
                    } else {
                        if (is_string($binding)) {
                            $executed->bindings[$i] = $binding;
                        }
                    }
                }

                $log = vsprintf($sql, $executed->bindings);
                $log = $log . ' [Runtime:'. $executed->time .'ms]';
                Log::channel('sqllog')->info($log, json_decode(json_encode($executed), true));
            }
        } catch (\Throwable $exception) {
            if (env('APP_DEBUG') == true) {
                throw $exception;
            }
        }
    }
}